<?php
class ContentsModel {
	public static function getByID ($id) {
		return self::get(array(
			'limit' => 1, 
			'where' => 'contents_id = ' . SleekPHP::db()->escSQL($id)
		));
	}

	public static function getByContentTypesID ($id) {
		return self::get(array(
			'where' => 'content_types_id = ' . SleekPHP::db()->escSQL($id)
		));
	}

	public static function get ($config) {
		return SleekPHP::db()->get('contents', $config);
	}

	public static function insert ($row) {
		return self::insertUpdate($row);
	}

	public static function update ($id, $row) {
		return self::insertUpdate($row, $id);
	}

	private static function insertUpdate ($row, $id = false) {
		$parent_contents_id		= isset($row['parent_contents_id']) ? $row['parent_contents_id'] : 'NULL';
		$content_types_id		= isset($row['content_types_id']) ? $row['content_types_id'] : 'NULL';
		$title					= isset($row['title']) ? $row['title'] : 'Untitled';
		$slug					= isset($row['slug']) ? $row['slug'] : urlize($title);
		$contents				= isset($row['contents']) ? $row['contents'] : '';

		$fields = array(
			'parent_contents_id'	=> $parent_contents_id, 
			'content_types_id'		=> $content_types_id, 
			'title'					=> $title, 
			'slug'					=> $slug, 
			'contents'				=> $contents
		);

		if ($id) {
			return SleekPHP::db()->update('contents', $id, $fields);
		}
		else {
			return SleekPHP::db()->insert('contents', $fields);
		}
	}

	public static function delete ($id) {
		return SleekPHP::db()->delete('contents', $id);
	}
}
